﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using SharePoint.Intranet.LinkChecker.TimerJobs;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using System.Web;

namespace SharePoint.Intranet.LinkChecker.Pages
{
    public class LinkCheckerHome : Page
    {
        private const string LINK_CHECKER_JOB_NAME = "LinkChecker";

        protected SiteAdministrationSelector SiteSelector;
        protected ListBox ReportsList;

        private void UpdateReportsList()
        {
            SPList ReportsDocLib = SPContext.Current.Web.Lists["Broken Link Scan Reports"];
            
            SPQuery ReportsForSiteQuery = new SPQuery();
            ReportsForSiteQuery.Query = string.Format(@"<Where>
                                            <Eq>
                                               <FieldRef Name='URL' />
                                               <Value Type='URL'>{0}</Value>
                                            </Eq>
                                          </Where>", SiteSelector.CurrentItem.Url);

            SPListItemCollection Reports = ReportsDocLib.GetItems(ReportsForSiteQuery);
            foreach (SPListItem Report in Reports)
            {
                ReportsList.Items.Insert(0, new ListItem(((DateTime)Report["Modified"]).ToString("dd/MM/yyyy hh:mm:ss"), Report.Url));
            }
        }

        public void btnImmediateScan_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(SiteSelector.CurrentItem.Url))
            {
                foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                {
                    if (job.Name == LINK_CHECKER_JOB_NAME)
                    {
                        job.Delete();
                    }
                }

                LinkCheckerTimerJob linkCheckerJob = new LinkCheckerTimerJob(LINK_CHECKER_JOB_NAME, site.WebApplication);
                linkCheckerJob.SiteCollectionUrl = site.ServerRelativeUrl;


                SPOneTimeSchedule schedule = new SPOneTimeSchedule();
                schedule.Time = DateTime.Now;
                linkCheckerJob.Schedule = schedule;
                linkCheckerJob.Update();
            }
        }

        public void SiteSelector_ContextChange(object sender, EventArgs e)
        {
            UpdateReportsList();
        }

        public void btnViewReport_Click(object sender, EventArgs e)
        {
            SPUtility.Redirect(SPContext.Current.Web.Url + "/" + ReportsList.SelectedValue, SPRedirectFlags.Default, HttpContext.Current);
        }
    }
}
